package com.cherry.androidcode.main

import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.cherry.androidcode.R
import com.cherry.androidcode.entity.MallHome
import com.cherry.androidcode.entity.MallHomeMultiple
import com.cherry.androidcode.mvp1.MVPFragment
import com.cherry.androidcode.util.resToColor
import com.yanyusong.y_divideritemdecoration.Y_Divider
import com.yanyusong.y_divideritemdecoration.Y_DividerBuilder
import com.yanyusong.y_divideritemdecoration.Y_DividerItemDecoration
import kotlinx.android.synthetic.main.fragment_main.*

/**
 * @author Cherry(dongmiansheng@gmail.com)
 * @since 2019/6/30
 */

class MainFragment : MVPFragment<MainContract.View, MainPresenter>(), MainContract.View {

    override val contentLayout = R.layout.fragment_main

    private val adapter by lazy {
        MainRecyclerAdapter()
    }

    //模拟分页
    private var page = 1

    //统一写死
    private val dividerDecoration by lazy {
        object : Y_DividerItemDecoration(activity) {
            override fun getDivider(itemPosition: Int): Y_Divider {
                //note 这里的尺寸参数是dp，不是px
                val paddingColor = R.color.transparent.resToColor()
                return Y_DividerBuilder()
                        .setTopSideLine(itemPosition == 0, paddingColor, 10f, 0f, 0f)
                        //不包括加载更多的view
                        .setBottomSideLine(itemPosition != adapter.itemCount - 1, paddingColor, 10f, 0f, 0f)
                        .setLeftSideLine(true, paddingColor, 10f, 0f, 0f)
                        .setRightSideLine(true, paddingColor, 10f, 0f, 0f)
                        .create()
            }
        }
    }

    override fun createPresenter() = MainPresenter()

    override fun createView() = this

    override fun setMultipleItemView(mallHome: MutableList<MallHomeMultiple<*>>?) {
        refresh.isRefreshing = false
        adapter.setNewInstance(mallHome)
    }

    override fun initView(view: View) {
        recyclerView.layoutManager = LinearLayoutManager(activity)
        recyclerView.addItemDecoration(dividerDecoration)
        recyclerView.adapter = adapter
        refresh.setOnRefreshListener {
            page = 1
            adapter.mainBottomNewProductProvider.unableLoadMore()
            mvpPresenter?.loadData()
        }
    }

    override fun onFragmentFirstVisible() {
        showLoading()
        mvpPresenter?.loadData()
    }

    fun loadMoreNewProductList() {
        mvpPresenter?.testLoadMoreNewProduct(++page)
    }

    override fun onTestLoadMoreNewProduct(productData: MutableList<MallHome.ProductData>?) {
        adapter.mainBottomNewProductProvider.addMoreData(productData)
    }


    companion object {
        fun newInstance() = MainFragment()
    }

}